package com.cn.ycy.filter;

import com.cn.ycy.exception.BusinessException;
import com.cn.ycy.util.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;

/**
 * 去除服务路径
 *
 * @author houwen
 */
//@Component
public class StripServicePathFilter implements GlobalFilter, Ordered {

    private static Logger logger= LoggerFactory.getLogger(StripServicePathFilter.class);

    @Override
    public int getOrder() {
        return 1000;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        logger.info("exec StripServicePathFilter");
        String newPath;
        try {
            newPath = RequestUtil.getPathInfo(exchange).getRealPath();
            logger.info("new path:{}", newPath);
        } catch (BusinessException e) {
            return Mono.error(e);
        }

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest newRequest = request.mutate().path(newPath).build();

        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());

        return chain.filter(exchange.mutate().request(newRequest).build());
    }

}
